import 'dart:convert';
import 'dart:convert' as convert;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:puppy_store/models/user_center_model.dart';
import 'package:puppy_store/pages/account/account_login_page.dart';
import 'package:puppy_store/pages/mine/mine_page.dart';
import 'package:puppy_store/utils/common_utils.dart';
import 'package:webview_flutter/webview_flutter.dart';

const htmlString = '''
<!DOCTYPE html>
<head>
<title>webview demo | IAM17</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, 
  maximum-scale=1.0, user-scalable=no,viewport-fit=cover" />
<style>
*{
  margin:0;
  padding:0;
}
body{
   background:#BBDFFC;  
   display:flex;
   flex-direction: column;
   justify-content:center;
   align-items:center;
   color:#C45F84;
   font-size:20px;
}
</style>
</head>
<html>
<body>

<div >大家好，我是 AdrianHwang </div>
<img id="avartar" src="" alt="头像" style="margin-top: 50px; width: 300px;">
<br/>
<div>我是Flutter应用传过来的信息: <Strong id="userInfo"></Strong></div>
<br/>
<button onclick="FlutterBack.postMessage('返回')">返回</button>
<br/>
<button onclick="FlutterUserIcon.postMessage('拍照')">拍照</button>
<script>
function addBase64SrcToImage(base64Data) {
    const imageElement = document.getElementById('avartar');
    if (imageElement) {
        // 为 image 标签设置 src 属性
        imageElement.src = base64Data;
    } else {
        console.error('未找到 id 为 aaaa 的 image 标签');
    }
}
</script>
</body>
</html>
''';

class UserCenterPage extends StatefulWidget {
  const UserCenterPage({super.key});

  @override
  State<UserCenterPage> createState() => _UserCenterPageState();
}

class _UserCenterPageState extends State<UserCenterPage> {
  // 网页控制器
  late WebViewController _webViewController;

  // 图片选择器
  final ImagePicker _imagePicker = ImagePicker();

  @override
  void initState() {
    _webViewController =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onProgress: (int progress) {
                // Update loading bar.
              },
              onPageStarted: (String url) {},
              onPageFinished: (String url) async {
                // 这里也可以拿到网页发过来的消息, 这里其实是注入我们自己的JS到Webview
                await Future.delayed(const Duration(milliseconds: 500));
                // var message = await webViewController
                //     .runJavaScriptReturningResult(
                //       'document.scrollingElement.scrollHeight',
                //     );
                // debugPrint("onPageFinished:webView网页中发过来的消息:$message");

                // 手动从WebView中获取数据 或者 调用WebView页面中的方法
                _webViewController.runJavaScript('''
                  document.getElementById('userInfo').innerHTML = '我真是服了,你个老六';
                  ''');
              },
              onHttpError: (HttpResponseError error) {},
              onWebResourceError: (WebResourceError error) {},
              onNavigationRequest: (NavigationRequest request) {
                // 当碰到一些不支持的协议时, 比如 baiduboxapp:// 协议, 就不允许跳转
                if (request.url.startsWith('baiduboxapp://')) {
                  // 跳转到原生页面
                  return NavigationDecision.prevent;
                }
                // 继续原来的请求
                return NavigationDecision.navigate;
              },
            ),
          )
          // 返回上一页频道
          ..addJavaScriptChannel(
            "FlutterBack",
            onMessageReceived: (message) {
              // 返回上一页
              Navigator.pop(context);
            },
          )
          // 调用手机相机和相册频道
          ..addJavaScriptChannel(
            "FlutterUserIcon",
            onMessageReceived: (message) {
              // 调取相册或者摄像头
              _showSelectUserIconDialog();
            },
          )
          // 更新用户信息频道
          ..addJavaScriptChannel(
            "FlutterNewUser",
            onMessageReceived: (JavaScriptMessage message) async {
              // 更新本地缓存的用户信息
              Map userInfo = convert.json.decode(message.message);
              await saveUserInfo(userInfo);
              // 刷新用户信息头像和
              userInfoNotifier?.value = UserModel.fromjson(userInfo);
            },
          )
          // 退出登录频道
          ..addJavaScriptChannel(
            "FlutterUserLogout",
            onMessageReceived: (message) async {
              // 清空本地缓存的用户信息
              await saveUserInfo({});
              // 更新用户个人信息
              userInfoNotifier?.value = null;
              // 进入登录页
              Navigator.pushReplacement(
                context,
                CupertinoPageRoute(
                  builder: (BuildContext context) {
                    return AccountLoginPage();
                  },
                ),
              );
            },
          )
          // ..loadRequest(Uri.parse('https://baidu.com')); // 跳转到外部网页
          // ..runJavaScript("网页中的方法('${传递到网页中的参数}')"); 向网页中传递参数
          ..loadHtmlString(htmlString); // 运行静态网页

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _cameraAndGallery(ImageSource source) async {
    try {
      XFile? imageFile = await _imagePicker.pickImage(
        source: source,
        maxHeight: 1500, // 限定图片的宽高
        maxWidth: 1500,
      );

      // 网页回显用户头像
      if (imageFile == null) return;
      // 将头像文件转成字节类型
      List<int> imageFileBytes = await imageFile.readAsBytes();
      // 对图片进行base64编码
      String imageFileBase64Str = base64Encode(imageFileBytes);
      // 拼接base64的头部
      String base64Image = 'data:image/jpeg;base64,$imageFileBase64Str';
      // Flutter调用网页注入用户头像的JS方法(该jS方法需要传入头像Base64编码后的字符创)

      _webViewController.runJavaScript(
        "window.addBase64SrcToImage('${base64Image}');",
      );
    } catch (e) {
      EasyLoading.showToast('拍照程序出错!');
    }
  }

  /// 构建选择头像对话框：拍照或打开相册
  void _showSelectUserIconDialog() {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: (60.0 * 3) + 21.0,
          padding: EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
          child: Column(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Color(0xFFF7F7F8),
                  borderRadius: BorderRadius.circular(5.0),
                ),
                clipBehavior: Clip.antiAlias,
                child: Column(
                  children: [
                    GestureDetector(
                      onTap: () {
                        _cameraAndGallery(ImageSource.camera);
                        Navigator.of(context, rootNavigator: true).pop();
                      },
                      child: Container(
                        height: 60.0,
                        color: Colors.white,
                        alignment: Alignment.center,
                        child: Text(
                          '拍照',
                          style: TextStyle(color: Colors.black, fontSize: 16.0),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 1.0),
                      child: GestureDetector(
                        onTap: () {
                          _cameraAndGallery(ImageSource.gallery);
                          Navigator.of(context, rootNavigator: true).pop();
                        },
                        child: Container(
                          height: 60.0,
                          color: Colors.white,
                          alignment: Alignment.center,
                          child: Text(
                            '我的相册',
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: 16.0,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 10.0),
                child: GestureDetector(
                  onTap: () {
                    Navigator.of(context, rootNavigator: true).pop();
                  },
                  child: Container(
                    height: 60.0,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(5.0),
                    ),
                    clipBehavior: Clip.antiAlias,
                    child: Text(
                      '取消',
                      style: TextStyle(color: Colors.black, fontSize: 16.0),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: SafeArea(
        child: Container(
          // 这里放网页
          child: WebViewWidget(controller: _webViewController),
        ),
      ),
    );
  }
}
